package com.example.permissionservice.config;

import com.example.permissionservice.entity.Role;
import com.example.permissionservice.mapper.RoleMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

@Component
@RequiredArgsConstructor
@Slf4j
public class DataInitializer implements CommandLineRunner {

    private final RoleMapper roleMapper;

    @Override
    @Transactional
    public void run(String... args) {
        log.info("开始进行权限服务数据初始化...");
        initializeRole("user", 1);
        initializeRole("admin", 2);
        initializeRole("super_admin", 3);
        log.info("权限服务数据初始化完成。");
    }

    private void initializeRole(String roleCode, int roleId) {
        if (roleMapper.findByRoleCode(roleCode).isEmpty()) {
            try {
                Role newRole = new Role(roleId, roleCode);
                roleMapper.save(newRole);
                log.info("成功插入角色: {}", newRole);
            } catch (Exception e) {
                log.error("插入角色 {} (ID: {}) 失败", roleCode, roleId, e);
            }
        } else {
            log.info("角色 {} 已存在，无需插入。", roleCode);
        }
    }
} 